import {getUserInfo, logOut} from '../../api/user'
import {Message} from 'ant-design-vue'
import storage from '../../utils/storage'
import {LOGIN_TOKEN, LOGIN_USER} from "@/constent";
import router from "@/router";

/**
 * user，最终合并到总的store
 */
const state = {
    // 状态
    loginUser: {},
    // 路由
    routes: []
}
const actions = {
    // 与组件中数据对接
    // 发送数据请求，将结果提交mutations
    async getUserInfo(context) {
        // 获得结果
        let result = await getUserInfo();
        const {code, data, msg} = result;
        // 存放到vuex
        if (code === 200) {
            context.commit('SAVE_USERINFO', data.user);
            context.commit('SAVE_ROUTES', data.routes);
        } else {
            Message.error(msg);
            this.$router.replace("/user/login");
        }
    },
    // 直接保存用户信息
    saveUser(context, authObj) {
        context.commit('SAVE_USERINFO', authObj.user);
        context.commit('SAVE_ROUTES', authObj.routes);
    },

    // 退出
    logout(context) {
        context.commit('CLEAN_USERINFO', {});
    },

    // 错误处理
    errorHandler(context) {
        context.commit('ERROR_HANDLER', {});
    }
}

const mutations = {
    // 保存用户信息
    SAVE_USERINFO(state, value) {
        state.loginUser = value;
    },
    // 保存用户信息
    SAVE_ROUTES(state, value) {
        state.routes = value;
    },
    // 退出登录
    CLEAN_USERINFO(state, value) {
        logOut().then(res => {
            state.loginUser = value;
            storage.remove(LOGIN_USER);
            storage.remove(LOGIN_TOKEN);
            router.replace("/user/login");
            Message.success("退出登录成功!");
        }).catch(err => {
            console.log(err);
        })
    },
    ERROR_HANDLER(state, value) {
        state.loginUser = value;
        storage.remove(LOGIN_USER);
        storage.remove(LOGIN_TOKEN);
        let route = router.currentRoute;
        if (route.path !== '/user/register') {
            router.replace("/user/login");
        }
    }
}

const getters = {}
export default {
    state,
    actions,
    mutations,
    getters
}
